(library (config)
  (export load-config-file
          load-config-files
          get-configuration)
  (import
    (except (rnrs base) let-values map error)
    (only (guile)
          lambda* λ map)
    ;; third party libs
    (json)
    ;; custom libraries
    (prefix (lib logger) log:)
    (lib fileio)
    (lib filesystem)
    (fslib)
    (model)
    (data-abstraction)))


;; =============
;; CONFIGURATION
;; =============
(define json-file-extension?
  (λ (fname)
    (string=? (file-extension fname) "json")))


(define load-config-file
  (λ (loc)
    (get-document-from-file loc json->scm)))


(define load-config-files
  (λ (dir names)
    (map (λ (fname)
           (let ([full-location (fsing-join dir fname)])
             ;; make an alist
             (cons (file-name fname)
                   (load-config-file full-location))))
         names)))


(define get-configuration
  (lambda* (#:key
            (transportation-config-dir (fsing-join "config" "transportation"))
            (player-config-dir (fsing-join "config" "player"))
            (general-config-dir "config"))
    (let ([transportation-configs
           (load-config-files
            transportation-config-dir
            (get-files-from-directory transportation-config-dir
                                      #:filter-proc json-file-extension?))]
          [player-configs
           (load-config-files
            player-config-dir
            (get-files-from-directory player-config-dir
                                      #:filter-proc json-file-extension?))]
          [general-config
           (load-config-file
            (fsing-join general-config-dir "general.json"))])

      (values transportation-configs
              player-configs
              general-config))))
